package com.tulingxueyuan.mall.interceptor;

import cn.hutool.core.util.StrUtil;
import com.tulingxueyuan.mall.common.BaseContext;
import com.tulingxueyuan.mall.common.api.ResultCode;
import com.tulingxueyuan.mall.common.exception.ApiException;
import com.tulingxueyuan.mall.common.util.ComConstants;
//import com.tulingxueyuan.mall.modules.ums.model.UmsAdmin;
//import com.tulingxueyuan.mall.modules.ums.model.UmsResource;
//import com.tulingxueyuan.mall.modules.ums.service.UmsAdminService;
import com.tulingxueyuan.mall.modules.ums.model.UmsMember;
import com.tulingxueyuan.mall.modules.ums.service.UmsMemberService;
import com.tulingxueyuan.mall.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 作用： 验证 用户是否登录、菜单资源权限
 *
 */
public class    AuthInterceptor implements HandlerInterceptor {
    // 配置文件中的白名单secure.ignored.urls
    private List<String> urls;

    @Autowired
    private UmsMemberService umsMemberService;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、不需要登录就可以访问的路径——白名单
        // 获取当前请求   /admin/login
        String requestURI = request.getRequestURI();
        // Ant方式路径匹配 /**  ？  _
        PathMatcher matcher = new AntPathMatcher();
        for (String ignoredUrl : urls) {
            if(matcher.match(ignoredUrl,requestURI)){
                return  true;
            }
        }

        String jwt = request.getHeader(tokenHeader);
//       1： 判断是否存在  和  是否以token开头
        if (StrUtil.isBlank(jwt)||!jwt.startsWith(tokenHead)) throw new ApiException(ResultCode.UNAUTHORIZED);
//        存在  去除Bearer 得到后面的并解码 根据username查询redis缓存 如果缓存没有查数据库
        jwt = jwt.substring(tokenHead.length());
        String userName = jwtUtil.getUserNameFromToken(jwt);
        if (StrUtil.isBlank(userName)) throw new ApiException(ResultCode.UNAUTHORIZED);
//        如果username不为空则保存进threadlocal中
        BaseContext.setCurrentUserName(userName);
//         从服务器中查询
            UmsMember umsMember = umsMemberService.getAdminByUsername(userName);
            if (umsMember==null) throw new ApiException(ResultCode.UNAUTHORIZED);
        return true;
//        else {
//            //3、已登录用户，判断是否有资源访问权限  Todo:到时候用spring security实现
//            UmsAdmin umsAdmin = (UmsAdmin) request.getSession().getAttribute(ComConstants.FLAG_CURRENT_USER);
//            // 获取用户所有可访问资源
//            List<UmsResource> resourceList = umsAdminService.getResourceList(umsAdmin.getId());
//            for (UmsResource umsResource : resourceList) {
//                if(matcher.match( umsResource.getUrl(),requestURI)){
//                    return  true;
//                }
//            }
//            throw new ApiException(ResultCode.FORBIDDEN);
//        }
//        return false;
    }


    public List<String> getUrls() {
        return urls;
    }

    public void setUrls(List<String> urls) {
        this.urls = urls;
    }
}
